import { FC, useEffect, useState } from "react";
import { Table, Switch, Space, Button, Modal, Drawer, Card, Tag } from "antd";
import styles from "./index.module.less";
import { deleteUser, getUserDetailApi, getUserList, updateUserInfo } from "@/api/modules/user";
import { connect, useDispatch, useSelector } from "react-redux";
import { setUserColumn, setUserRow } from "@/redux/modules/user/action";
import { RootState } from "@/redux";
import { User } from "@/api/interface";
import { ColumnsType } from "antd/lib/table";
import useMessage from "@/hooks/useMessage";
import { useNavigate } from "react-router-dom";
import useModal from "@/hooks/useModal";
import useVisible from "@/hooks/useVisible";
import UserDetail from "../UserDetails";
import UserEdit from "../UserEdit";
import UserAdd from "../UserAdd";
import UserFilter from "../UserFilter";

const UserList: FC = () => {
	const navigate = useNavigate();
	const userColumn = useSelector<RootState, RootState["user"]>(state => state.user.userColumn);
	const dispatch = useDispatch();
	const { contextHolder, success, error } = useMessage();

	const { id, isModalOpen, openModal, closeModal } = useModal();
	const [total, setTotal] = useState<number>(0);

	// 获取
	const getUserData = async (pageNum: number = 1, pageSize: number = 10, wrapper?: Partial<User.UserInfo>) => {
		const res = await getUserList(pageNum, pageSize, wrapper);
		if (res.code == 200) {
			dispatch(setUserColumn(res.data.rows));
			setTotal(res.data.total);
		}
	};
	const onChangePage = (page: number) => {
		getUserData(page, 10);
	};

	// 更新
	const updateUserData = async (userInfo: Partial<User.UserInfo>) => {
		const res = await updateUserInfo(userInfo);
		if (res.code == 200) {
			dispatch(setUserRow(userInfo));
			success("修改成功");
		} else {
			error("修改失败");
		}
	};

	const onChangeCheck = (checked: boolean, row: User.UserInfo) => {
		const rowData: Partial<User.UserInfo> = {
			...row,
			is_admin: checked
		};
		updateUserData(rowData);
	};

	// 删除
	const removeUser = async () => {
		const res = await deleteUser(id);
		if (res.code == 200) {
			getUserData();
			success("删除成功");
		} else {
			error("删除失败");
		}
		closeModal();
	};

	useEffect(() => {
		getUserData();
	}, []);

	const columns: ColumnsType<User.UserInfo> = [
		{
			title: "账号",
			dataIndex: "user_name",
			key: "user_name",
			align: "center"
		},
		{
			title: "用户名",
			dataIndex: "name",
			key: "name",
			align: "center"
		},
		{
			width: 200,
			title: "角色",
			dataIndex: "roles",
			key: "roles",
			align: "center",
			render: (_: any, row: User.UserInfo) => {
				return (
					<>
						{row.roles && row.roles.length !== 0
							? (row?.roles as User.Role[]).map(item => (
									<Tag color="cyan" key={item.id}>
										{item.name}
									</Tag>
							  ))
							: "无"}
					</>
				);
			}
		},
		{
			title: "是否为管理员",
			dataIndex: "is_admin",
			key: "is_admin",
			align: "center",
			render: (_: any, row: User.UserInfo) => {
				return (
					<>
						<Switch defaultChecked={row.is_admin} onChange={(checked: boolean) => onChangeCheck(checked, row)} />
					</>
				);
			}
		},
		// {
		// 	title: "头像",
		// 	dataIndex: "user_image",
		// 	key: "user_image",
		// 	align: "center"
		// },
		{
			title: "创建时间",
			dataIndex: "createdAt",
			key: "createAt",
			align: "center"
		},
		{
			title: "Action",
			key: "action",
			render: (_, row) => (
				<Space size="middle">
					<a onClick={() => openRole(row.id)}>角色</a>
					<a onClick={() => openDetail(row.id)}>详情</a>
					<a onClick={() => openEdit(row.id)}>修改</a>
					<a onClick={() => openModal(row.id)}>删除</a>
				</Space>
			)
		}
	];

	const [userDetail, setUserDetail] = useState<User.UserInfo>({} as User.UserInfo);
	const fetchUserDetail = async (id: number) => {
		const res = await getUserDetailApi(id);
		setUserDetail(res.data);
	};

	const {
		openDetail,
		openEdit,
		setDetailVisible,
		detailVisible,
		addVisible,
		setAddVisible,
		editVisible,
		setEditVisible,
		onCloseAdd,
		onCloseEdit
	} = useVisible(fetchUserDetail, getUserData);

	const openRole = (userId: number) => {
		navigate("/user/userrole", { state: { id: userId } });
	};

	const listExtra = (
		<div style={{ display: "flex", gap: 8 + "px" }}>
			<Button type="primary" onClick={() => setAddVisible(true)}>
				新增
			</Button>
			<Button type="primary" onClick={() => getUserData()}>
				刷新
			</Button>
		</div>
	);

	const onSearch = (data?: User.UserInfo) => {
		getUserData(1, 10, data);
	};

	return (
		<div className={styles.root}>
			{contextHolder}
			<UserFilter onSearch={onSearch}></UserFilter>
			<Card title="数据列表" extra={listExtra}>
				<Table
					bordered={true}
					dataSource={userColumn as any}
					columns={columns}
					pagination={{ total: total, onChange: onChangePage }}
				/>
			</Card>

			<Modal title="提醒" mask={false} visible={isModalOpen} onOk={removeUser} onCancel={closeModal}>
				确定删除该用户吗
			</Modal>

			<Drawer title="详情" placement="right" width={500} onClose={() => setDetailVisible(false)} visible={detailVisible}>
				<UserDetail user={userDetail}></UserDetail>
			</Drawer>

			<Drawer
				title="新增"
				placement="right"
				width={500}
				onClose={() => {
					setAddVisible(false);
				}}
				visible={addVisible}
			>
				<UserAdd onComfirm={onCloseAdd}></UserAdd>
			</Drawer>

			<Drawer
				title="修改"
				placement="right"
				width={500}
				onClose={() => {
					setEditVisible(false);
				}}
				visible={editVisible}
			>
				<UserEdit user={userDetail} type="edit" onComfirm={onCloseEdit}></UserEdit>
			</Drawer>
		</div>
	);
};

const mapDispatchToProps = (dispatch: any) => {
	return {
		setUserColumn: () => {
			dispatch(setUserColumn);
		}
	};
};
export default connect(null, mapDispatchToProps)(UserList);
